package com.rhino.security.handler;

import com.alibaba.fastjson.JSON;
import com.rhino.security.constants.SecurityConstants;
import com.rhino.security.utils.JwtTokenUtil;
import com.rhino.security.vo.JWTTokenVO;
import com.rhino.security.vo.JwtUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 登录成功处理器,登录成功，把用户信息存入SecurityContextHolder，并且生成token返回给前端。
 */
@Component
public class JwtAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        JwtUser userDetails = (JwtUser) authentication.getPrincipal();
        SecurityContextHolder.getContext().setAuthentication(authentication);
        renderToken(response, jwtTokenUtil.getJWTToken(userDetails));
    }

    /**
     * 渲染返回 token 页面,因为前端页面接收的都是Result对象，故使用application/json返回
     *
     * @param response
     * @throws IOException
     */
    public void renderToken(HttpServletResponse response, JWTTokenVO jwtTokenVO) throws IOException {
        response.setContentType(SecurityConstants.APPLICATION_JSON_UTF8_VALUE);
        PrintWriter writer = response.getWriter();
        //返回前端登录成功的格式，前端处理
        writer.write(JSON.toJSONString(jwtTokenVO));
        writer.close();
    }
}